# -*- coding: utf-8 -*-
# owner: shenyi

# src/core/credentials.py
from typing import Dict, Optional, Any
from ..constants import PROVIDER_CREDENTIAL_META, SUPPORTED_PROVIDERS
from .config import Config

class CloudCredentials:
    """
    多云凭据统一管理器。
    支持阿里云、腾讯云、华为云、AWS、Google Cloud。
    凭据字段定义来自 constants.PROVIDER_CREDENTIAL_META。
    """

    def __init__(self, config: Optional[Config] = None):
        if config is not None:
            self._config = config
        else:
            # 延迟导入，避免循环依赖
            from .app import config as global_config
            if hasattr(global_config, 'get'):
                self._config = global_config
            else:
                raise RuntimeError(
                    "CloudCredentials requires a Config instance or global config setup. "
                    "Call setup_app() first."
                )

    def _get_credential_value(self, key: Optional[str]) -> Optional[str]:
        """安全获取配置值，避免 KeyError"""
        if not key:
            return None
        return self._config.get(key)

    def aliyun(self) -> Dict[str, Optional[str]]:
        meta = PROVIDER_CREDENTIAL_META["aliyun"]
        return {
            "access_key_id": self._get_credential_value(meta["key"]),
            "access_key_secret": self._get_credential_value(meta["secret"]),
            "region_id": self._get_credential_value(meta.get("region")),
            "endpoint": self._get_credential_value("ALIYUN_ENDPOINT"),  # 非标准字段，保留
        }

    def tencent(self) -> Dict[str, Optional[str]]:
        meta = PROVIDER_CREDENTIAL_META["tencent"]
        return {
            "secret_id": self._get_credential_value(meta["key"]),  # 腾讯叫 SecretId
            "secret_key": self._get_credential_value(meta["secret"]),
            "region": self._get_credential_value(meta.get("region")),
        }

    def huawei(self) -> Dict[str, Optional[str]]:
        meta = PROVIDER_CREDENTIAL_META["huawei"]
        return {
            "access_key_id": self._get_credential_value(meta["key"]),
            "access_key_secret": self._get_credential_value(meta["secret"]),
            "project_id": self._get_credential_value(meta.get("project_id")),
        }

    def aws(self) -> Dict[str, Optional[str]]:
        meta = PROVIDER_CREDENTIAL_META["aws"]
        return {
            "access_key_id": self._get_credential_value(meta["key"]),
            "access_key_secret": self._get_credential_value(meta["secret"]),
            "region": self._get_credential_value(meta.get("region")),
        }

    def google(self) -> Dict[str, Optional[str]]:
        meta = PROVIDER_CREDENTIAL_META["google"]
        return {
            "project_id": self._get_credential_value(meta.get("project_id")),
            "credentials_file": self._get_credential_value(meta.get("credentials_file")),
            # Google 通常用文件，不返回 key/secret
        }

    def get(self, provider: str) -> Dict[str, Optional[str]]:
        if provider not in SUPPORTED_PROVIDERS:
            raise ValueError(f"Unsupported cloud provider: {provider}. "
                             f"Supported: {', '.join(SUPPORTED_PROVIDERS)}")

        method_map = {
            "aliyun": self.aliyun,
            "tencent": self.tencent,
            "huawei": self.huawei,
            "aws": self.aws,
            "google": self.google,
        }
        return method_map[provider]()
